package com.maomi.coder;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;

import java.io.IOException;

/**
 * Created by lucky on 2019-03-28.
 */
public class ReOpenDemo {

    public static void print(IndexSearcher is, TopDocs topDocs) throws IOException {
        //查询评分
        System.out.println("评分为:"+topDocs.getMaxScore());

        for (ScoreDoc scoreDoc:topDocs.scoreDocs) {
            //实际的文档查询
            Document doc = is.doc(scoreDoc.doc);
            if(doc != null){
                System.out.println(doc.get("id") + "-" + doc.get("author") + "-" + doc.get("bookName") + "-" + doc.get("price"));
            }
        }
    }

    public static void main(String[] args) throws IOException, ParseException {
        String path = System.getProperty("java.io.tmpdir") + "index_lucene";
        LuceneDemo demo = new LuceneDemo();
        IndexWriter writer = demo.getWriter(path);

        IndexReader indexReader = DirectoryReader.open(demo.getDirectory(path));

        IndexSearcher is = new IndexSearcher(indexReader);

        QueryParser parser = new QueryParser("id",new StandardAnalyzer());

        //*:* 默认会转换成MatchAllQuery
        Query query = parser.parse("*:*");

        TopDocs topDocs = is.search(query, 10);

        //打印查询内容
        print(is,topDocs);

        Document document = new Document();
        document.add(new StringField("id","5", Field.Store.YES));
        document.add(new StringField("author","zhangsan", Field.Store.YES));
        document.add(new TextField("bookName","lucene",Field.Store.YES));
        document.add(new StringField("price","150", Field.Store.YES));
        //添加一个文档
        writer.addDocument(document);

        writer.commit();

        print(is,topDocs);

        //近实搜索
        DirectoryReader directoryReader = DirectoryReader.openIfChanged((DirectoryReader) indexReader);
        if(directoryReader != null){
            indexReader.close();
        }
        is = new IndexSearcher(directoryReader);

        TopDocs topDocs2 = is.search(query, 10);

        //打印查询内容
        print(is,topDocs2);

        directoryReader.close();
    }

}
